<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Catalog_import extends CI_Controller {
	var $perpage = 20;
		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/catalog/', 'Импорт товаров');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }
//	   function smiles() {
//	   $smiles = array("http://telzakaz.ru/components/com_jcomments/images/smiles/laugh.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/lol.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/smile.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/wink.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/cool.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/normal.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/whistling.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/redface.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/sad.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/cry.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/surprised.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/confused.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/sick.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/shocked.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/sleeping.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/tongue.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/rolleyes.gif",
//"http://telzakaz.ru/components/com_jcomments/images/smiles/unsure.gif");
//foreach ($smiles as $smile) {
//	$seg = explode("/", $smile);
//	$fname = $seg[sizeof($seg) - 1];
//	copy($smile, "./data/images/smiles/".$fname);
//}
//	   }
//	   function im($from = 0) {
//			include_once './simple_html_dom.php';
//			$this->load->library('thumbnail');
//			error_reporting(1);
//			$pages = $this->db->select()->from('catalog_items')->where('item_parent', 13)->limit(10, $from)->get()->result_array();
//			if (sizeof($pages) <= 0) { echo "end"; exit(); }
//			foreach ($pages as $page) {
//			$k = 1;
//			$snippet = "";
//				$url = "http://telzakaz.ru".$this->catalog_service_model->get_item_link($page['item_id']);
//				dump($url);
//				$html = file_get_html($url);
//				if (is_object($html)) {
//					$p = $html->find('div.vmRecent', 1);
//					if (is_object($p)) {
//						$z = $p->find('a', 0);
//						dump($z->href);
//						$o = $page['item_id'];
//
//						mkdir('./uploads/catalog_items/' . $o);
//						mkdir('./uploads/catalog_items/' . $o . '/small');
//						mkdir('./uploads/catalog_items/' . $o . '/middle');
//						chmod('./uploads/catalog_items/' . $o, 0777);
//						chmod('./uploads/catalog_items/' . $o . '/small', 0777);
//						chmod('./uploads/catalog_items/' . $o . '/middle', 0777);
//						$seg = explode("/", $z->href);
//						$fname = $seg[sizeof($seg) - 1];
//						$path = './uploads/catalog_items/' . $o . '/' . $fname;
//						copy('http://telzakaz.ru/' . $z->href, $path);
//						$im = getimagesize($path);
//						if ($im[0] > 140 || $im[1] > 190) {
//							$this->thumbnail->output($path, './uploads/catalog_items/'.$o.'/small/'.$fname, array('width' => 140, 'height' => 190, 'method' => THUMBNAIL_METHOD_SCALE_MAX, 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
//						} else {
//							copy($path, './uploads/catalog_items/'.$o.'/small/'.$fname);
//						}
//						if ($im[0] > 250 || $im[1] > 340) {
//							$this->thumbnail->output($path, './uploads/catalog_items/'.$o.'/middle/'.$fname, array('width' => 250, 'height' => 340, 'method' => THUMBNAIL_METHOD_SCALE_MAX, 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
//						} else {
//							copy($path, './uploads/catalog_items/'.$o.'/middle/'.$fname);
//						}
//
//						$im_db_data['photo_id'] = 0;
//						$im_db_data['photo_file'] = $fname;
//						$im_db_data['photo_item'] = $o;
//						$im_db_data['photo_order'] = $k;
//						$im_db_data['photo_main'] = ($k==1?1:0);
//						$this->db->insert('catalog_images', $im_db_data);
//
//						//$snippet = strip_tags($z, "<strong>");
//					} else {
//						//$snippet = "";
//					}
//					//dump($snippet);
//					//$this->db->set('item_snippet', $snippet)->where('item_id', $page['item_id'])->update('catalog_items');
//				}
//			}
//			$new = $from + 10;
//			echo '<META HTTP-EQUIV="REFRESH" CONTENT="1;URL=/admin/catalog_import/im/'.$new.'/">';
//	   }
//	   function snippets($from = 0) {
//			include_once './simple_html_dom.php';
//			error_reporting(1);
//			$pages = $this->db->select()->from('catalog_items')->limit(10, $from)->get()->result_array();
//			$k=0;
//			if (sizeof($pages) <= 0) { echo "end"; exit(); }
//			foreach ($pages as $page) {
//			$k++;
//			$snippet = "";
//				$url = "http://telzakaz.ru".$this->catalog_service_model->get_item_link($page['item_id']);
//				dump($url);
//				$html = file_get_html($url);
//				if (is_object($html)) {
//					$o = $html->find('div.vmRecent', 0);
//					if (is_object($o)) {
//						$z = $o->find('div', 0)->innertext;
//						$snippet = strip_tags($z, "<strong>");
//					} else {
//						$snippet = "";
//					}
//					dump($snippet);
//					$this->db->set('item_snippet', $snippet)->where('item_id', $page['item_id'])->update('catalog_items');
//				}
//			}
//			$new = $from + 10;
//			echo '<META HTTP-EQUIV="REFRESH" CONTENT="1;URL=/admin/catalog_import/snippets/'.$new.'/">';
//	   }
//
//	   function comments($from = 0) {
//
//			$dbcfg['hostname'] = 'localhost';
//			$dbcfg['username'] = 'root';
//			$dbcfg['password'] = '';
//			$dbcfg['database'] = 'telzakaz';
//			$dbcfg['dbdriver'] = 'mysql';
//			$dbcfg['dbprefix'] = '';
//			$dbcfg['pconnect'] = TRUE;
//			$dbcfg['db_debug'] = FALSE;
//			$dbcfg['cache_on'] = FALSE;
//			$dbcfg['cachedir'] = $_SERVER['DOCUMENT_ROOT'].'/application/cache/db/';
//			$dbcfg['char_set'] = 'utf8';
//			$dbcfg['dbcollat'] = 'utf8_general_ci';
//			$dbcfg['swap_pre'] = '';
//			$dbcfg['autoinit'] = TRUE;
//			$dbcfg['stricton'] = FALSE;
//
//			$d = $this->load->database($dbcfg, true, true);
//
//		   $items = $this->db->select()->from('catalog_items')->limit(20, $from)->get()->result_array();
//		   if (sizeof($items) <= 0) { echo "end"; exit(); }
//		   foreach ($items as $item) {
//			   $item['item_curl'] = str_replace("/", "", str_replace(".html", "", $item['item_curl']));
//			   $result = $d->select()->from('jos_menu')->where('alias', $item['item_curl'])->get()->row_array();
//			   preg_match("/^product_id=([0-9]+)\n/", $result['params'], $num);
//			   dump($num[1]);
//			   $comments = $d->select()->from('jos_jcomments')->where('object_group', 'com_virtuemart')->where('object_id', $num[1])->get('','','',1)->result_array();
//			   //dump($comments);
//			   foreach ($comments as $c) {
//				   $db_data['opinion_id'] = $c['id'];
//				   $db_data['opinion_parent'] = $c['parent'];
//				   $db_data['opinion_user'] = 0;
//				   $db_data['opinion_item'] = $item['item_id'];
//				   $db_data['opinion_text'] = $c['comment'];
//				   $db_data['opinion_status'] = $c['published'];
//				   $db_data['opinion_date'] = strtotime($c['date']);
//				   $db_data['opinion_ip'] = $c['ip'];
//				   $db_data['opinion_name'] = $c['name'];
//				   $db_data['opinion_email'] = "";
//				   $db_data['opinion_shop'] = "";
//				   $db_data['opinion_answer'] = "";
//				   $this->db->insert('catalog_opinions', $db_data);
//			   }
//		   }
//		   $new = $from + 20;
//			echo '<META HTTP-EQUIV="REFRESH" CONTENT="1;URL=/admin/catalog_import/comments/'.$new.'/">';
//	   }
	   function index() {
			$form = new jQuickForm('simple');
			$form->setAttribute('enctype', 'multipart/form-data');
			$form->addElement('file', 'file')->setLabel('Фаил для загрузки')->setComment('XML фаил экспорта из 1С');
			$form->insertInputSubmit("Загрузить фаил импорта");

			if ($_SERVER['REQUEST_METHOD'] == "POST") {
					$config['upload_path'] = './uploads/import/';
					$config['allowed_types'] = 'xls';
					$config['encrypt_name']  = true;
					$config['remove_spaces']  = true;
					$this->load->library('upload', $config);
					if (!$this->upload->do_upload('file')) {
						$this->session->set_flashdata('error', $this->upload->display_errors());
						redirect('admin/catalog_import');
					} else {
						$file = $this->upload->data();
						redirect('admin/catalog_import/go/'.str_replace(".xls","",$file['file_name']).'/');
					}
			}

//			$data['last'] = $this->db->select_max('item_imported_date')->from('catalog_items')->get()->row_array();
			$data['unset'] = $this->db->select()->from('catalog_items')->where('item_parent', '-1')->count_all_results();
			$data['form'] = $form."";
			$data['js'] = jQuickForm::js()->getJsAll();
			$this->layout->view('admin/catalog_import/index', $data);
	   }
	public function go($file,$ch=2)	{
//		$this->output->enable_profiler(TRUE);
		$this->db->truncate('catalog_import');
//		$out = read_file('./uploads/import/'.$file);
//		$xml = simplexml_load_string($out);
		// xls
		$this->load->helper('reader');
		$data = new Spreadsheet_Excel_Reader();
		$data->setOutputEncoding('UTF-8');
//		$data->setOutputEncoding('Windows-1251');
		$data->read("./uploads/import/".$file.".xls");
//		dump($data->sheets[0]);
//		$xlsmails = array();
//		$xlsnames = array();
		$pr_data['file'] = $file;
		$pr_data['check'] = ($ch + 500);
		$pr_data['max'] = $data->sheets[0]['numRows'];
		if($pr_data['check'] > $pr_data['max']){
			$pr_data['check'] = $pr_data['max'];
		}
		if($ch >= $pr_data['max']){
			redirect('admin/catalog_import/fix');
		}
//		for ($i = $ch; $i <= $data->sheets[0]['numRows']; $i++) {
		for ($i = $ch; $i <= $pr_data['check']; $i++) {
			$brand = htmlspecialchars(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][2]));
			if($brand != " " && $brand != "" ){
				$brand_exist = $this->db->select()->from('catalog_brands')->where('brand_title',$brand)->limit(1)->get()->row_array();
				if(sizeof($brand_exist) > 0){
					$p_data['item_brand'] = $brand_exist['brand_id'];
				} else {
					$this->db->set('brand_title',$brand);
					$this->db->set('brand_status',1);
					$this->db->set('brand_order',1000);
					$this->db->insert('catalog_brands');
					$p_data['item_brand'] = $this->db->insert_id();
				}
				
			} else {
				$p_data['item_brand'] = 0;
			}
			$p_data['item_title'] = htmlspecialchars(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][3]));
			$p_data['item_code'] = htmlspecialchars(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][4]));
			$p_data['item_price'] = htmlspecialchars(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][5]));
			$p_data['item_have'] = htmlspecialchars(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][6]));
			$p_data['item_number'] = htmlspecialchars(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][1]));
			$p_data['item_status'] = 1;
			$p_data['item_order'] = 1000;
			$p_data['item_parent'] = -1;
			$check = $this->db->select()->from('catalog_items')->where('item_number',$p_data['item_number'])->get()->result_array();
			if(sizeof($check) > 0){
				foreach($check as $el){
					$this->db->set($p_data);
					$this->db->where('item_id',$el['item_id']);
					$this->db->update('catalog_items');
				}
			} else {
				$this->db->insert('catalog_items', $p_data);
			}
//			for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
////				dump(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][$j]));
//			//if($data->sheets[0]['cells'][$i][$j] != '') {
////				dump(iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][$j]));
//				if($j == 2){
//					$import['brand'] = iconv("cp1251", "utf-8", $data->sheets[0]['cells'][$i][$j]);
//					if($import['brand'] != " " && $import['brand'] != "" ){
////						dump($import['brand']);
//					} else {
////						echo 0;
//					}
//				}
//			}
//				$xlsmails[] = $data->sheets[0]['cells'][$i][$j];
//				echo $data->sheets[0]['cells'][$i][$j]."<br />";
			//}
//			$j = 2;
//			$xlsnames[] = $data->sheets[0]['cells'][$i][$j];
//			$j = 1;
//				echo "<hr />";
		}
		$this->layout->view('admin/catalog_import/progress',$pr_data);
//		exit();
//		foreach($xlsmails as $key => $xlsmail){
//			$p_data['mailbase_mail'] = $xlsmail;
//			$p_data['mailbase_name'] = $xlsnames[$key];
//			$p_data['mailbase_group'] = $id;
//			$this->db->set('mailbase_mail',$p_data['mailbase_mail']);
//			$this->db->set('mailbase_name',$p_data['mailbase_name']);
//			$this->db->set('mailbase_group',$p_data['mailbase_group']);
//			$this->db->insert('mailbase');
//		}
		// xls

		//xml
//		$GLOBALS['data'] = array();
//		$this->rec($xml);
//		$i = 0;
//		foreach ($GLOBALS['data'] as $k => $item) {
//			$i++;
//			$prices = "";
//			foreach ($item as $kk => $el) {
//				preg_match_all('/р\.\s{0,1}([0-9]{0,3})/', $el->attributes()->Наименование, $matches);
//				if (is_numeric($matches[1][0])) {
//					$z = intval($matches[1][0]);
//					$prices .= $z.":".floatval($el->attributes()->Цена)."\n";
//				}
//				$name = trim(str_replace($k, "", str_replace($matches[0][0], "", $el->attributes()->Наименование)));
//				$name = str_replace("-1 ", "", $name);
//				$name = str_replace("-2 ", "", $name);
//				$name = str_replace("-3 ", "", $name);
//				$name = trim($name);
//			}
//			if ($el->attributes()->Наименование != "") {
//			$db_data['import_id'] = 0;
//			$db_data['import_title'] = $name;
//			$db_data['import_code'] = $k;
//			$db_data['import_number'] = "Мод.".$k;
//			$db_data['import_sizes'] = $prices;
//			$this->db->insert('catalog_import', $db_data);
//			}
//		}

//		redirect('admin/catalog_import/check');
	}
	function rec($obj, $level = 0) {
		$GLOBALS['data'];
		foreach ($obj->Группа as $group) {
			if (sizeof($group->Номенклатура) > 0) {
				foreach ($group->Номенклатура as $nom) {
					$id = (string) str_replace("Мод.", "", $group->attributes()->Наименование);
					$GLOBALS['data'][$id][] = $nom;
				}
			}
			if (sizeof($group->Группа) > 0) {
				$this->rec($group, $levelup);
			}
		}
	}
	function check() {
		$pages = $this->db->select()->from('catalog_import')->get()->result_array();
		foreach ($pages as $page) {
			$new[] = $page['import_number'];
		}
		$all_items = $this->db->select()->from('catalog_items')->where('item_parent != ', '-2')->get()->result_array();
		foreach ($all_items as $item) {
			if (!in_array($item['item_code'], $new)) {
				$this->db->set('item_parent', '-2')->where('item_code', $item['item_id'])->update('catalog_items');
			}
		}
		foreach ($pages as $key => $page) {
			$check = $this->db->select()->from('catalog_items')->where('item_code', $page['import_number'])->get()->row_array();
			if (sizeof($check) > 0) {
				$this->db->set('item_sizes', $page['import_sizes'])->set('item_title', $page['import_title'])->where('item_id', $check['item_id'])->update('catalog_items');
				$this->db->where('import_id', $page['import_id'])->delete('catalog_import');
				unset($pages[$key]);
			} else {
				$db_data['item_id'] = 0;
				$db_data['item_title'] = $page['import_title'];
				$db_data['item_code'] = $page['import_number'];
				$db_data['item_parent'] = '-1';
				$db_data['item_desc'] = '';
				$db_data['item_sizes'] = $page['import_sizes'];
				$db_data['item_colors'] = '';
				$db_data['item_new'] = 0;
				$db_data['item_hit'] = 0;
				$db_data['item_popular'] = 0;
				$db_data['item_status'] = 1;
				$db_data['item_price'] = 0;
				$db_data['item_oldprice'] = 0;
				$db_data['item_unit'] = 'шт.';
				$db_data['item_imported_date'] = time();
				$db_data['item_order'] = 10000;
				$this->db->insert('catalog_items', $db_data);
			}
		}
		redirect('admin/catalog_import/fix');
	}
	function fix() {
		$data['pages'] = $pages = $this->db->select()->from('catalog_items')->where('item_parent', '-1')->order_by('item_title')->get()->result_array();
		$data['parents'] = $this->catalog_service_model->show_to_droppabel();
		if (sizeof($pages) > 0) {
			$this->layout->view('admin/catalog_import/fix', $data);
		} else {
			$this->session->set_flashdata('msg', 'Импорт успешно произведен, записи обновлены');
			redirect('admin/catalog_import');
		}
	}
	function move() {
		$p_data = $this->input->post();
		$ids = explode(":", $p_data['ids']);
		foreach ($ids as $id) {
			if ($id != "") {
				$this->db->set('item_parent', $p_data['parent'])->where('item_id', $id)->update('catalog_items');
			}
		}
		echo "ok";
	}
	function delete() {
		$p_data = $this->input->post();
		$ids = explode(":", $p_data['ids']);
		foreach ($ids as $id) {
			if ($id != "") {
				$this->db->where('item_id', $id)->delete('catalog_items');
			}
		}
		echo "ok";
	}
}
